import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import domainService from '../services/domains';
import type { DomainSummary, DomainDetail, CreateDomainRequest, DomainOperation } from '../types/api';

interface DomainStore {
  // 状态
  domains: DomainSummary[];
  currentDomain: DomainDetail | null;
  loading: boolean;
  error: string | null;
  
  // 操作方法
  fetchDomains: (connectionId: string, includeInactive?: boolean) => Promise<void>;
  createDomain: (connectionId: string, data: CreateDomainRequest) => Promise<void>;
  deleteDomain: (connectionId: string, domainName: string) => Promise<void>;
  performDomainOperation: (connectionId: string, domainName: string, operation: DomainOperation) => Promise<void>;
  getDomainDetail: (connectionId: string, domainName: string) => Promise<void>;
  refreshDomainStatus: (connectionId: string, domainName: string) => Promise<void>;
  
  // 工具方法
  getDomainByName: (domainName: string) => DomainSummary | undefined;
  clearError: () => void;
}

export const useDomainStore = create<DomainStore>()(
  devtools(
    (set, get) => ({
      domains: [],
      currentDomain: null,
      loading: false,
      error: null,

      // 获取所有虚拟机
      fetchDomains: async (connectionId: string, includeInactive: boolean = true) => {
        set({ loading: true, error: null });
        
        try {
          console.log('开始获取虚拟机列表...');
          const response = await domainService.listDomains(connectionId, includeInactive);
          console.log('获取到的虚拟机数据:', response);
          
          set({ domains: response || [], loading: false });
          console.log('虚拟机列表已更新');
        } catch (error: any) {
          console.error('获取虚拟机列表失败:', error);
          set({
            error: error.message || '获取虚拟机列表失败',
            loading: false
          });
        }
      },

      // 创建新虚拟机
      createDomain: async (connectionId: string, data: CreateDomainRequest) => {
        set({ loading: true, error: null });
        
        try {
          console.log('开始创建虚拟机:', data);
          const result = await domainService.createDomain(connectionId, data);
          console.log('虚拟机创建成功:', result);
          
          // 重新获取虚拟机列表
          await get().fetchDomains(connectionId);
        } catch (error: any) {
          console.error('创建虚拟机失败:', error);
          set({
            error: error.message || '创建虚拟机失败',
            loading: false
          });
          throw error;
        }
      },

      // 删除虚拟机
      deleteDomain: async (connectionId: string, domainName: string) => {
        set({ loading: true, error: null });
        
        try {
          console.log('开始删除虚拟机:', domainName);
          await domainService.deleteDomain(connectionId, domainName);
          console.log('虚拟机删除成功');
          
          // 重新获取虚拟机列表
          await get().fetchDomains(connectionId);
        } catch (error: any) {
          console.error('删除虚拟机失败:', error);
          set({
            error: error.message || '删除虚拟机失败',
            loading: false
          });
          throw error;
        }
      },

      // 执行虚拟机操作
      performDomainOperation: async (connectionId: string, domainName: string, operation: DomainOperation) => {
        set({ loading: true, error: null });
        
        try {
          console.log(`开始执行虚拟机操作: ${operation}`, domainName);
          
          switch (operation) {
            case 'start':
              await domainService.startDomain(connectionId, domainName);
              break;
            case 'shutdown':
              await domainService.shutdownDomain(connectionId, domainName);
              break;
            case 'force-stop':
              await domainService.forceStopDomain(connectionId, domainName);
              break;
            case 'reboot':
              await domainService.rebootDomain(connectionId, domainName);
              break;
            case 'suspend':
              await domainService.suspendDomain(connectionId, domainName);
              break;
            case 'resume':
              await domainService.resumeDomain(connectionId, domainName);
              break;
            default:
              throw new Error(`不支持的操作: ${operation}`);
          }
          
          console.log(`虚拟机操作 ${operation} 成功`);
          
          // 重新获取虚拟机列表和详情
          await get().fetchDomains(connectionId);
          if (get().currentDomain?.name === domainName) {
            await get().getDomainDetail(connectionId, domainName);
          }
          
          // 操作完成后清除加载状态
          set({ loading: false });
        } catch (error: any) {
          console.error(`虚拟机操作 ${operation} 失败:`, error);
          set({
            error: error.message || `虚拟机操作 ${operation} 失败`,
            loading: false
          });
          throw error;
        }
      },

      // 获取虚拟机详情
      getDomainDetail: async (connectionId: string, domainName: string) => {
        set({ loading: true, error: null });
        
        try {
          console.log('开始获取虚拟机详情:', domainName);
          const detail = await domainService.getDomainDetail(connectionId, domainName);
          console.log('获取虚拟机详情成功:', detail);
          
          set({ currentDomain: detail, loading: false });
        } catch (error: any) {
          console.error('获取虚拟机详情失败:', error);
          set({
            error: error.message || '获取虚拟机详情失败',
            loading: false
          });
          throw error;
        }
      },

      // 刷新虚拟机状态
      refreshDomainStatus: async (connectionId: string, domainName: string) => {

        try {
          const status = await domainService.getDomainStatus(connectionId, domainName);
          
          // 更新本地状态
          const { domains } = get();
          const updatedDomains = domains.map(domain => 
            domain.name === domainName 
              ? { ...domain, state: status.state }
              : domain
          );
          
          set({ domains: updatedDomains });
          
          // 如果当前详情页是这个虚拟机，也更新详情
          if (get().currentDomain?.name === domainName) {
            await get().getDomainDetail(connectionId, domainName);
          }
        } catch (error: any) {
          console.error('刷新虚拟机状态失败:', error);
        }
      },

      // 工具方法
      getDomainByName: (domainName: string) => {
        const { domains } = get();
        return domains.find(domain => domain.name === domainName);
      },

      clearError: () => {
        set({ error: null });
      },
    }),
    {
      name: 'domain-store',
    }
  )
);

// 选择器
export const useDomains = () => 
  useDomainStore(state => state.domains);

export const useCurrentDomain = () => 
  useDomainStore(state => state.currentDomain);

export const useDomainLoading = () => 
  useDomainStore(state => state.loading);

export const useDomainError = () => 
  useDomainStore(state => state.error);